package com.everyline.lib_common.http

import com.blankj.utilcode.util.LogUtils
import com.everyline.lib_common.BuildConfig
import com.everyline.lib_common.global.ConfigKeys
import com.everyline.lib_common.global.Configurator
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 * Created by on 2021/3/20.
 * 天天挂线
 *  746608431@qq.com
 *  描述:TODO
 */

class RetrofitClientUtils {

    private val TAG = RetrofitClientUtils::class.java.simpleName

    companion object {
        val instance = SingleTonProvider.holder
    }

    private object SingleTonProvider {
        val holder = RetrofitClientUtils()
    }

    private val httpLoggingInterceptor = HttpLoggingInterceptor(object :
        HttpLoggingInterceptor.Logger {
        override fun log(message: String) {
            LogUtils.d(TAG,message)
        }
    }).also {
        it.level = HttpLoggingInterceptor.Level.BODY
    }

    private val okHttpClient = OkHttpClient.Builder()
        .also {
            if (BuildConfig.DEBUG) {
                it.addInterceptor(httpLoggingInterceptor)
            }
        }
        .build()

    private val retrofit = Retrofit.Builder()
        .baseUrl(Configurator.instance.getConfiguration<String>(ConfigKeys.WEB_API_HOST))
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    fun <T> create(service: Class<T>): T {
        return retrofit.create(service)
    }
}